package com.campsys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campsys.domain.TManagerTeacher;
import com.campsys.domain.TSysUser;
import com.campsys.domain.param.TeacherAddParam;
import com.campsys.domain.param.UserAddParam;
import com.campsys.mapper.TeacherMapper;
import com.campsys.mapper.UserMapper;
import com.campsys.mapping.TeacherMapping;
import com.campsys.mapping.UserMapping;
import com.campsys.service.ITeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, TManagerTeacher> implements ITeacherService {

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private UserMapper userMapper;

    @Transactional
    @Override
    public Boolean addTeacher(TeacherAddParam teacherAddParam) {

        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode("123456");

        UserAddParam userAddParam = TeacherMapping.INSTANCE.toUser(teacherAddParam);
        userAddParam.setLoginName(teacherAddParam.getTeacherName());
        TSysUser tSysUser = UserMapping.INSTANCE.to(userAddParam);
        tSysUser.setPassword(encode);
        tSysUser.setStatus("1");
        int rs1 = userMapper.insert(tSysUser);

        TManagerTeacher tManagerTeacher = TeacherMapping.INSTANCE.to(teacherAddParam);
        tManagerTeacher.setLoginId(tSysUser.getId());
        int rs2 = teacherMapper.insert(tManagerTeacher);

        boolean rs3 = userMapper.addRoleIdByUserId(tSysUser.getId(),3l);

        return rs1 == 1 && rs2 == 1 && rs3 ? true : false;
    }

    @Transactional
    @Override
    public Boolean deleteTeacher(Long id) {

        TManagerTeacher tManagerTeacher = teacherMapper.selectById(id);
        tManagerTeacher.setStatus(1l);

        TSysUser user = new TSysUser();
        user.setId(tManagerTeacher.getLoginId());
        user.setStatus("2");

        int rs1 = userMapper.updateById(user);

        int rs2 = teacherMapper.updateById(tManagerTeacher);
        return rs1 == 1 && rs2 == 1 ? true : false;
    }
}
